package com.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.constant.MessageConstant;
import com.exception.CustomException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mapper.CheckGroupMapper;
import com.pageResult.PageResult;
import com.pojo.CheckGroup;
import com.query.QueryPageBean;
import com.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass =CheckGroupService.class )
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupMapper checkGroupMapper;

    //查询检查组（分页+条件）
    @Override
    public PageResult selectByQueryString(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize(),true);
        Page<CheckGroup> page = checkGroupMapper.selectByQueryString(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }
    /*删除*/
    @Transactional
    @Override
    public void delete(Integer id) throws CustomException {
        //删除之前先查看套餐里面有没有引用检查组
        Integer count = checkGroupMapper.isUseInSemeal(id);
        if(count>0){
            throw new CustomException(MessageConstant.SETMEAL_IN_USE);
        }
        //先解散，删除检查组与检查项的关系
        checkGroupMapper.delCheckGroupCheckItemByGroupId(id);
        //再来删除检查组
        checkGroupMapper.deleteByPrimaryKey(id);
    }

    //添加
    @Transactional
    @Override
    public void add(CheckGroup checkGroup,Integer [] ItemIds) {
        //1.先插入数据进检查组
        checkGroupMapper.insertSelective(checkGroup);
        //如果有选择检查项则在第三方表插入数据
        if(ItemIds!=null && ItemIds.length>0){
            checkGroupMapper.addCheckGroupAndCheckItem(checkGroup.getId(),ItemIds);
        }
    }
    //根据id查询
    @Override
    public CheckGroup queryById(Integer id) {
        return checkGroupMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer[] queryByCheckItemId(Integer GroupId) {
        return checkGroupMapper.queryByCheckItemId(GroupId);
    }

    //修改
    @Transactional
    @Override
    public void update(CheckGroup checkGroup,Integer [] ItemIds) {
        checkGroupMapper.updateByPrimaryKeySelective(checkGroup);
        //如果有选择检查项则在第三方表插入数据
        if(ItemIds!=null && ItemIds.length>0){
            //1.先删除本来就有的数据
            checkGroupMapper.deleteByCheckGroup(checkGroup.getId());
            //2.再重新添加数据
            checkGroupMapper.addCheckGroupAndCheckItem(checkGroup.getId(),ItemIds);
        }else {
            checkGroupMapper.deleteByCheckGroup(checkGroup.getId());
        }
    }

    @Override
    public List<CheckGroup> queryAll() {
        return checkGroupMapper.selectByExample(null);
    }
}
